import { Router } from "../../utils/common.js";
import { RemoteDataService } from '../../utils/remoteDataService.js';
import { TokenStorage, UserStorage } from "../../utils/storageSevice.js";
import { CACHE } from "../../utils/cache.js";

Page({
  data: {
    userInfo: {},
    loading: true,
    petList: []
  },
  onLoad: function(){
    let that = this;
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.code) {
          RemoteDataService.wxLogin({ jsCode: res.code }).then(result => {
            if (result && result.code=="000") {
              TokenStorage.setData(result.accessToken);
              that.checkSettingsStatus();
              if(result.petsCount && parseInt(result.petsCount)>0){
                that.getMyPetList()
              }else{
                that.navToPetAddPre()
              }
            }
          }).catch(err => {
            that.setData({
              loading: false
            });
          })
        }
      },
      fail: err => {
        console.log(err);
      }
    })
  },
  onShow: function(){
    console.log("CACHE.isIndexFirstIn==" + CACHE.isIndexFirstIn);
    if (CACHE.isIndexFirstIn){
      CACHE.isIndexFirstIn = false
    }else{
      this.getMyPetList()
    }
  },
  checkSettingsStatus: function () {//检查授权状态
    var that = this;
    /**
     * 将多层回调函数封装成promise，达到同步的效果
     * 使代码便于阅读和定点错误
     */
    getSet().then(result => {
      return nogetSet();
    }).then(results => {
    }, function (err) {
      console.log("网络失败");
    })

    //查看用户是否第一次授权授权
    function getSet() {
      var sets = new Promise((resolve, reject) => {
        //检查授权情况
        wx.getSetting({
          success: function (res) {
            //获取用户信息
            wx.getUserInfo({
              withCredentials: false,
              lang: "zh_CN",
              success: function (res) {
                UserStorage.setData(res.userInfo);
                that.setData({
                  userInfo: res.userInfo
                });
                RemoteDataService.updateUserInfo(res.userInfo).then(result => {
                  if (result && result.code == "000") {
                    console.log(result.msg)
                    if(result.userId){
                      let userInfo = UserStorage.getData()
                      userInfo.userId = result.userId
                      UserStorage.setData(userInfo);
                    }
                  }
                }).catch(err => {
                  
                })
              },
              fail: function (err) {
                // 授权失败，马上调起弹窗，强制用户授权
                resolve(err);
              }
            })
          },
          fail: function (err) {
            reject(err);
          }
        });
      });
      return sets;
    };
    // 用户未授权的情况下
    function nogetSet() {
      var nosets = new Promise((resolve, reject) => {
        wx.showModal({
          title: '用户未授权',
          content: '亲，为了不影响您使用汪牌的服务，请重新确认授权信息！',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.openSetting({
                success: (res) => {
                  console.log(res)
                },
                fail: function (err) {
                  console.log(err);
                }
              })
            }
          }
        })
      });
      return nosets;
    }
  },
  getMyPetList: function(){
    let that = this
    let params = {}
    wx.showNavigationBarLoading()
    RemoteDataService.getUserPetList(params).then(result => {
      if (result && result.code == "000") {
        console.log(result.pets)
        that.setData({
          petList: result.pets
        })
        CACHE.userPetCount = result.pets.length
        console.log("CACHE.userPetCount", CACHE.userPetCount)
      }
      wx.hideNavigationBarLoading()
    }).catch(err => {
      wx.hideNavigationBarLoading()
    })
  },
  navToPetDet: function(e){
    let params = {
      petId: e.currentTarget.dataset.petid
    }
    Router.navigateTo("../dogdet/dogdet", params);
  },
  navToPetAddPre: function () {
    Router.navigateTo("../dogaddpre/dogaddpre");
  }
})
